$:.unshift File.join(File.dirname(__FILE__), "..","v")

require 'net/pop'
require 'uri'
require 'painter'

class ZPOP < Net::POP3

	def ZPOP.url?(addr)
		begin
			uri = URI.parse(addr)
			if uri.class != URI::Generic
				Painter.err('Address can not start with "http" or "ftp"')
				return false
			else
				return addr
			end
			rescue URI::InvalidURIError
				Painter.err('Invalid address')
				return false
    end		
	end

	def ZPOP.port?(p)
		return (0<p and p<65536)
	end

	def ZPOP.email?(m)
		if m.count('@') != 1
			return false
		else
			user, server = m.split('@')
			return ZPOP.url?(server)
		end
	end
	
	def initialize(addr, p)
		if (ZPOP.url?(addr) and ZPOP.port?(p))
			super(addr,p,true) #isapop=true
		else
			Painter.err("Error in server or port")
		end
	end

	def apop= (isapop)
	  @apop=isapop
	end

	def start(account, pwd)
		begin
			super(account,pwd)
			return self
		rescue Net::POPAuthenticationError
			if self.apop? then
				self.apop = false
				retry
			else
				Painter.deb
			end
		end
	end

end
